import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:qh_music/src/shared/enum/playlist_mode.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AudioPlaylistModeController extends StatefulWidget {
  final Player player;
  const AudioPlaylistModeController({super.key, required this.player});

  @override
  State<AudioPlaylistModeController> createState() =>
      _AudioPlaylistModeControllerState();
}

class _AudioPlaylistModeControllerState
    extends State<AudioPlaylistModeController> {
  final String playerListModeKey = "playerListMode";
  late int _modeIndex = PlayMode.loop.index;

  PlayMode get _mode => PlayMode.values[_modeIndex];

  @override
  void initState() {
    super.initState();
    _initPlayMode();
  }

  @override
  Widget build(BuildContext context) {
    return Tooltip(
      enableTapToDismiss: false,
      message: _mode.getText(context),
      child: IconButton(
        onPressed: _onPress,
        icon: _mode.icon,
      ),
    );
  }

  void _onPress() async {
    _recordPlayMode();
    await _setPlaylistMode();
  }

  Future<void> _initPlayMode() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    int modeIndex =
        sharedPreferences.getInt(playerListModeKey) ?? PlayMode.loop.index;
    setState(() {
      _modeIndex =
          modeIndex >= PlayMode.values.length || modeIndex < 0 ? 0 : modeIndex;
    });
    _setPlaylistMode();
  }

  Future<void> _setPlaylistMode() async {
    switch (_mode) {
      case PlayMode.sequence:
        await widget.player.setPlaylistMode(PlaylistMode.none);
        return;
      case PlayMode.single:
        await widget.player.setShuffle(false);
        await widget.player.setPlaylistMode(PlaylistMode.single);
        return;
      case PlayMode.loop:
        await widget.player.setShuffle(false);
        await widget.player.setPlaylistMode(PlaylistMode.loop);
        return;
      case PlayMode.shuffle:
        await widget.player.setShuffle(true);
        await widget.player.setPlaylistMode(PlaylistMode.loop);
        return;
    }
  }

  void _recordPlayMode() {
    int index = _modeIndex + 1;
    if (index >= PlayMode.values.length) {
      index = 0;
    }
    setState(() {
      _modeIndex = index;
    });
    SharedPreferences.getInstance().then((value) {
      value.setInt(playerListModeKey, index);
    });
  }
}
